package com.lingx.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.security.PrivateKey;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.lingx.utils.Utils;
import com.lingx.web.LingxApp;
import com.lingx.web.core.ApiServer;
import com.lingx.web.core.ExitServer;
import com.lingx.web.core.FileUploadServer;
import com.lingx.web.local.rsa.SecurityRsa;

@Component(value="lingxStartupService")
public class StartupService {
	@Resource
	private ConfigService configService;
	@Resource
	private LingxService lingxService;
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private ApplicationContext spring;

	@PostConstruct
	public void startup() {
		LingxApp.SPRINGCONTEXT=spring;
       
        try {
            ApiServer server = new ApiServer(Integer.parseInt(configService.getWebHttpPort()));
            // 设置Http最大内容长度（默认 为10M）
            server.setMaxContentLength(1024 * 1024 * 50);
    		System.out.println("正在启动API接口监听服务，端口:"+configService.getWebHttpPort());
    		new Thread(server).start();
    		
    		System.out.println("正在启动File上传下载服务，端口:"+configService.getFileHttpPort());
            FileUploadServer fs=new FileUploadServer(Integer.parseInt(configService.getFileHttpPort()));
            new Thread(fs).start();

    		System.out.println("正在启动系统退出监听服务，端口:"+configService.getExitPort());
            new Thread(new ExitServer(Integer.parseInt(configService.getExitPort()))).start();
            //每次启动都改变更新密钥
            lingxService.setConfigValue("lingx.update.secret", this.lingxService.uuid());
            
            this.init();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	public void init() {
		String roleId=lingxService.getConfigValue("lingx.super.role.code", "6e0362e8-100e-11e5-b7ab-74d02b6b5f61");//lingx.super.role.code
		List<Map<String,Object>> list=this.jdbcTemplate.queryForList("select id from tlingx_menu");
		for(Map<String,Object> map:list) {
			if(this.jdbcTemplate.queryForObject("select count(*) from tlingx_role_menu where role_id=? and menu_id=?", Integer.class,roleId,map.get("id"))==0) {
				this.jdbcTemplate.update("insert into tlingx_role_menu(id,role_id,menu_id)values(?,?,?)",lingxService.uuid(),roleId,map.get("id"));
			}
		}
	}
	public void close() {
		System.out.println("正在退出系统...");
		System.exit(0);
	}
	
}
